/*
 * Sesame Inc.
 * Copyright (c) 2009 All Rights Reserved.
 */
package com.sesame.serviceimpl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.security.providers.encoding.Md5PasswordEncoder;

import com.sesame.dao.AnswerDAO;
import com.sesame.dao.AskDAO;
import com.sesame.dao.CollectDAO;
import com.sesame.dao.ComplaintDAO;
import com.sesame.dao.FindPasswordDAO;
import com.sesame.dao.MessageDAO;
import com.sesame.dao.NoticeDAO;
import com.sesame.dao.UserDAO;
import com.sesame.domain.Answer;
import com.sesame.domain.Ask;
import com.sesame.domain.Collect;
import com.sesame.domain.Complaint;
import com.sesame.domain.FindPassword;
import com.sesame.domain.Message;
import com.sesame.domain.Notice;
import com.sesame.domain.User;
import com.sesame.service.SearchService;
import com.sesame.service.UserService;
import com.sesame.toolkit.Encrypt;
import com.sesame.toolkit.Page;

/**
 * @author shubeta
 * 
 */
public class UserServiceImpl implements UserService {

    private UserDAO userDAO;
    private MessageDAO messageDAO;
    private FindPasswordDAO findPasswordDAO;
    private ComplaintDAO complaintDAO;
    private MailSender mailSender;
    private SimpleMailMessage mail;
    private FindPassword findPassword;
    private Ask ask;
    private AskDAO askDAO;
    private Answer answer;
    private AnswerDAO answerDAO;
    private SearchService searchService;
    private CollectDAO collectDAO;
    private NoticeDAO noticeDAO;

    public void setUserDAO(UserDAO userDAO) {
        this.userDAO = userDAO;
    }

    public void setMessageDAO(MessageDAO messageDAO) {
        this.messageDAO = messageDAO;
    }

    public void setFindPasswordDAO(FindPasswordDAO findPasswordDAO) {
        this.findPasswordDAO = findPasswordDAO;
    }

    public void setComplaintDAO(ComplaintDAO complaintDAO) {
        this.complaintDAO = complaintDAO;
    }

    public void setMailSender(MailSender mailSender) {
        this.mailSender = mailSender;
    }

    public void setMail(SimpleMailMessage mail) {
        this.mail = mail;
    }

    public void setFindPassword(FindPassword findPassword) {
        this.findPassword = findPassword;
    }

    public void setAsk(Ask ask) {
        this.ask = ask;
    }

    public void setAskDAO(AskDAO askDAO) {
        this.askDAO = askDAO;
    }

    public void setAnswer(Answer answer) {
        this.answer = answer;
    }

    public void setAnswerDAO(AnswerDAO answerDAO) {
        this.answerDAO = answerDAO;
    }

    public void setSearchService(SearchService searchService) {
        this.searchService = searchService;
    }

    public void setCollectDAO(CollectDAO collectDAO) {
        this.collectDAO = collectDAO;
    }

    public void setNoticeDAO(NoticeDAO noticeDAO) {
        this.noticeDAO = noticeDAO;
    }

    public boolean register(HttpServletRequest request, User user, Map model) {
        User emailUser = userDAO.getUserByEmail(user.getEmail().toLowerCase());
        User nickNameUser = userDAO.getUserByNickName(user.getNickName());

        if (emailUser == null && nickNameUser == null) {
            md5(user);
            userDAO.addUser(user);
            searchService.index(user);
            User tempUser = userDAO.getUserByEmail(user.getEmail());
            sendMessage(tempUser.getId());
            return true;
        } else {
            if (emailUser != null) {
                model.put("error_email", "该邮箱已被注册！");
            }
            if (nickNameUser != null) {
                model.put("error_nickName", "该昵称已被使用！");
            }
            return false;
        }
    }

    public boolean validatePassword(User user, String confirmPassword, Map model) {
        if (confirmPassword.equals(user.getPassword())) {
            return true;
        } else {
            model.put("error_password", "两次密码输入不一致！");
            return false;
        }
    }

    public boolean validateCode(HttpServletRequest request,
            String identifyCode, Map model) {

        String rand = (String) request.getSession().getAttribute("rand");
        if (identifyCode.equals(rand)) {
            return true;
        } else {
            model.put("error_identifyCode", "验证码错误！");
            return false;
        }
    }

    public boolean findPassword(User user, Map model) {
        User dbUser = userDAO.getUserByEmail(user.getEmail());
        if (dbUser != null) {
            String mailText = dbUser.getNickName() + "，你好\n";
            mailText = mailText + "请点击以下链接接设置新密码，该链接仅可使用一次。";
            mailText = mailText + "如果无法点击，请复制该链接到地址栏中。\n";
            Date createTime = new Date();
            String timeStamp = createTime.getTime() + "";
            String md5Code = Encrypt.MD5(user.getId() + timeStamp);
            String URL = "http://localhost:8080/SesameAlbum/newPassword.html?code="
                    + md5Code;

            findPassword.setCode(md5Code);
            findPassword.setEmail(user.getEmail());
            findPassword.setCreateTime(createTime);
            findPasswordDAO.addFindPassword(findPassword);

            mailText = mailText + URL + "\n";

            mail.setFrom("阿里芝麻网络相册");
            mail.setTo(user.getEmail());
            mail.setSubject("找回密码－阿里芝麻网络相册");
            mail.setText(mailText);
            mailSender.send(mail);
            return true;

        } else {
            model.put("error_email", "该邮箱不存在！");
            return false;
        }
    }

    public boolean newPassword(String code, User user, Map model) {

        FindPassword dbFindPassword = findPasswordDAO
                .getFindPasswordByCode(code);
        if (dbFindPassword != null) {
            User dbUser = userDAO.getUserByEmail(dbFindPassword.getEmail());
            dbUser.setPassword(user.getPassword());
            md5(dbUser);
            userDAO.updateUserPassword(dbUser);
            findPasswordDAO.deleteFindPasswordByCode(code);
            return true;
        } else {
            model.put("error_newPassword", "该链接不存在或已失效！");
            return false;
        }
    }

    public boolean modifyPassword(String oldPassword, User user, Map model) {

        User dbUser = userDAO.getUserById(user.getId());
        if (dbUser.getPassword().equals(md5(oldPassword))) {
            md5(user);
            userDAO.updateUserPassword(user);
            return true;
        } else {
            model.put("error_oldPassword", "原密码不正确！");
            return false;
        }
    }

    public boolean editUserinfo(User user, Map model) {
        userDAO.updateUserDetail(user);
        return true;
    }

    public boolean modifyHeadPic(User user, Map model) {
        userDAO.updateHeadPic(user);
        user = userDAO.getUserById(user.getId());
        searchService.reindex(user);
        return true;
    }

    public void report(Complaint complaint, Map model) {
        complaintDAO.addComplaint(complaint);
    }

    public User showUser(Integer id) {
        return userDAO.getUserById(id);
    }

    public User showUser(String email) {
        return userDAO.getUserByEmail(email);
    }

    public void newAsk(String title, String content, HttpServletRequest request) {
        ask.setTitle(title);
        ask.setContent(content);
        Integer userId = (Integer) request.getSession().getAttribute("userId");
        String nickName = (String) request.getSession()
                .getAttribute("nickName");
        String headPic = (String) request.getSession().getAttribute("headPic");
        ask.setUserId(userId);
        ask.setNickName(nickName);
        Date createTime = new Date();
        ask.setCreateTime(createTime);
        ask.setHeadPic(headPic);
        ask.setReplyAmount(0);
        ask.setVisitAmount(0);
        askDAO.addAsk(ask);

    }

    public List<Ask> listAsk(Page page) {
        return askDAO.getAllAsk(page);

    }

    public void newAnswer(Integer askId, String content,
            HttpServletRequest request) {
        answer.setAskId(askId);
        answer.setContent(content);
        Integer userId = (Integer) request.getSession().getAttribute("userId");
        String nickName = (String) request.getSession()
                .getAttribute("nickName");
        String headPic = (String) request.getSession().getAttribute("headPic");
        answer.setUserId(userId);
        answer.setCreateTime(new Date());
        answer.setNickName(nickName);
        answer.setHeadPic(headPic);
        answerDAO.addAnswer(answer);
    }

    public List<Answer> listAnswer(Integer askId) {
        return answerDAO.getAllAnswer(askId);
    }

    public Ask showAsk(Integer askId) {
        return askDAO.getAskById(askId);
    }

    private void sendMessage(Integer userId) {
        Message message = new Message();
        message.setSenderId(1);
        message.setReceiverId(userId);
        message.setSender(userDAO.getUserById(1).getNickName());
        message.setReceiver(userDAO.getUserById(userId).getNickName());
        message.setTitle("你已经成功注册");
        message.setContent("你已经成功注册，欢迎使用芝麻网络相册！");
        message.setState("0");
        message.setFlag("both");
        message.setSendTime(new Date());
        messageDAO.addMessage(message);

    }

    private User md5(User user) {
        Md5PasswordEncoder md5 = new Md5PasswordEncoder();
        user.setPassword(md5.encodePassword(user.getPassword(), new String(
                "canyouguessme")));
        return user;
    }

    private String md5(String password) {
        Md5PasswordEncoder md5 = new Md5PasswordEncoder();
        password = md5.encodePassword(password, new String("canyouguessme"));
        return password;
    }

    public void deleteAsk(Integer askId) {
        answerDAO.deleteAnswerByAskId(askId);
        askDAO.deleteAskById(askId);
    }

    public void deleteAnswer(Integer answerId) {
        answerDAO.deleteAnswerById(answerId);
    }

    public void newCollect(Collect collect) {
        if (collectDAO.getCollectByImageId(collect) == null) {
            collectDAO.addCollect(collect);
        }

    }

    public List<Collect> listCollect(Integer userId) {
        return collectDAO.getCollectByUserId(userId);
    }

    public void deleteCollect(Integer collectId) {
        collectDAO.deleteCollectById(collectId);
    }

    public Integer getAskCount() {
        return askDAO.getAskCount();
    }

    public List<Collect> listTopCollect(Integer userId) {
        return collectDAO.getTopCollectByUserId(userId);
    }
    
    public List<Notice> listTopNotice() {
        return noticeDAO.getTopNotice();
    }
    
    public Notice showNotice(Integer id) {
        return noticeDAO.getNoticeById(id);
    }

}